<?php

namespace App\Http\Controllers;

use App\Library\HandleCommentTag;
use App\Models\Shop;
use App\Models\TuanInfo;
use App\Models\TuanOrder;
use App\Models\User;
use App\Models\UserComment;
use App\Models\Integrallist;
use Exception;
use Illuminate\Http\Request;

/**
 * 评论相关
 */
class CommentController extends Controller
{
    /**
     * 店铺的用户评论
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function shop_comments(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $shop_id = $request->get('shop_id');
            $limit   = $request->get('limit') ?? 5;
            if (empty($shop_id)) {
                throw new Exception('缺少参数！');
            }
            $shop     = Shop::where(['shop_id' => $shop_id])->first();
            $comments = UserComment::where(['shop_id' => $shop_id])
                ->where(function ($query) use ($request) {
                    if ($request->has('type') && $request->get('type') == 2) {
                        $query->where('is_img', 2);
                    }
                })->orderBy('create_time', 'desc')->limit($limit)->get();

            $data['total'] = $shop->user_comment->count();
            $data['star']  = intval(($shop->score / $shop->score_num) * 10) / 10;
            //店铺评价标签
            $tags                 = $shop->comment_tags()->pluck('tag')->toArray();
            $data['comment_tags'] = HandleCommentTag::entry($tags); //处理评价标签（获取数组）
            //处理数据
            foreach ($comments as $key => $value) {
                $data['list'][$key]['nickname']    = $value->user->nickname;
                $data['list'][$key]['headimg']     = $value->user->headimg;
                $data['list'][$key]['score']       = $value->score;
                $data['list'][$key]['contents']    = $value->contents;
                $data['list'][$key]['create_time'] = date('Y-m-d', $value->create_time);
                //处理评价图片
                $imgs = [];
                foreach ($value->comment_img as $k => $val) {
                    $imgs[$k]['url'] = $val->url;
                }
                $data['list'][$key]['imgs'] = $imgs;
            }

            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    public function tuan_comments(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $tuan_id = $request->get('tuan_id');
            $limit   = $request->get('limit') ?? 5;
            if (empty($tuan_id)) {
                throw new Exception('缺少参数！');
            }
            $tuan     = TuanInfo::where(['tuan_id' => $tuan_id])->first();
            $comments = UserComment::where(['tuan_id' => $tuan_id])
                ->where(function ($query) use ($request) {
                    if ($request->has('type') && $request->get('type') == 2) {
                        $query->where('is_img', 2);
                    }
                })->orderBy('create_time', 'desc')->limit($limit)->get();

            $data['total'] = $tuan->user_commends->count();
            $data['star']  = intval(($tuan->user_commends->avg('score') * 10)) / 10;
            //店铺评价标签
            $tags                 = $tuan->comment_tags()->pluck('tag')->toArray();
            $data['comment_tags'] = HandleCommentTag::entry($tags); //处理评价标签（获取数组）
            //处理数据
            foreach ($comments as $key => $value) {
                $data['list'][$key]['nickname']    = $value->user->nickname;
                $data['list'][$key]['headimg']     = $value->user->headimg;
                $data['list'][$key]['score']       = $value->score;
                $data['list'][$key]['contents']    = $value->contents;
                $data['list'][$key]['create_time'] = date('Y-m-d', $value->create_time);
                //处理评价图片
                $imgs = [];
                foreach ($value->comment_img as $k => $val) {
                    $imgs[$k]['url'] = $val->url;
                }
                $data['list'][$key]['imgs'] = $imgs;
            }

            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 发布评论
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function release_comment(Request $request)
    {
        try {
            $status   = 0;
            $data     = [];
            $user_id  = $request->get('user_id') ?? 0;
            $order_id = $request->get('order_id');
            $score    = $request->get('score');
            $type     = $request->get('type');
            $contents = $request->get('contents') ?? '默认好评';
            $imgs     = $request->get('imgs');
            if (count($imgs) > 0) {
                $is_img = 2;
            } else {
                $is_img = 1;
            }
            if (empty($order_id) || empty($score) || empty($type)) {
                throw new Exception('缺少参数！');
            }
            $order = TuanOrder::where(['order_id' => $order_id])->first();
            if (!$order) {
                throw new Exception('未找到订单');
            }
            $res = UserComment::create([
                'order_id'    => $order_id,
                'userID'      => $user_id,
                'shop_id'     => $order->shop_id,
                'tuan_id'     => $order->tuan_id,
                'score'       => $score,
                'contents'    => $contents,
                'reply'       => null,
                'create_time' => time(),
                'create_ip'   => $request->getClientIp(),
                'closed'      => 1,
                'is_show'     => 1,
                'type'        => $type,
                'is_img'      => $is_img,
            ]);
            if (count($imgs) > 0) {
                foreach ($imgs as $val) {
                    $res->comment_img()->create([
                        'comment_id' => $res->comment_id,
                        'url'        => $val,
                        'url_oss'    => $val,
                    ]);
                }
            }
            //修改订单状态为已评价
            TuanOrder::where(['order_id' => $order_id])->update([
                'order_status' => 3,
            ]);
            //如果用户id不为0，评价获得积分
            if ($user_id != 0) {
                $integral = intval($order->price / 100); //积分是否等于订单实付金额？
                $user     = User::where(['userID' => $user_id])->first();
                $user->increment('integral', $integral); //用户积分自增
                //写入积分纪录表
                Integrallist::create([
                    'userID'   => $user_id,
                    'integral' => $integral,
                    'type'     => 1,
                    'property' => 3,
                    'id'       => $order_id,
                    'note'     => '评价获得' . $integral . '积分',
                    'time'     => time(),
                ]);
                $data['integral'] = $integral;
            }
            //其他待评价订单
            $orders = TuanOrder::where(['user_id' => $user_id, 'order_status' => 2])
                ->orderBy('create_time', 'desc')->get();
            //处理数据
            $arr = [];
            foreach ($orders as $key => $value) {
                $arr[$key]['order_id']    = $value->order_id;
                $arr[$key]['create_time'] = date('Y-m-d', $value->create_time);
                if (count($value->tuan_info) > 0) {
                    $arr[$key]['name'] = $value->tuan_info->title;
                } else if (count($value->shop) > 0) {
                    $arr[$key]['name'] = $value->shop->shop_name;
                } else {
                    $arr[$key]['name'] = null;
                }
            }
            $data['orders'] = $arr;

            $status = 1;
            $msg    = '评论成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }
        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }
}
